<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
    <style>
        *{margin:0;padding:0;}
        body{
            background:#000;
            overflow:hidden;
        }
    </style>
</head>
<body>
    <canvas id="mycanvas"></canvas>
</body>
<script>
    var mycanvas = document.querySelector('#mycanvas');
    var ctx = mycanvas.getContext('2d');
    mycanvas.width = window.innerWidth;
    mycanvas.height = window.innerHeight;//等价于document.documentElement.clientHeight;
    //绘制需要绘制的球的数组
    var ballsArr = [];
    //绘制球的类
    function Ball(x,y){
        this.x = x;//绘制球的圆心的x坐标点
        this.y = y;//y坐标点
        this.r = 30;//球的半径
        this.color = 'rgb('+this.randomC()+','+this.randomC()+','+this.randomC()+')';
        this.dx = parseInt(Math.random()*8-4);/*要运动的圆心x坐标点的速度,-4-4的随机数*/
        this.dy = parseInt(Math.random()*8-4);/*要运动的圆心y坐标点的速度,-4-4的随机数*/
        //把我自己这个球加到需要绘制的球的类当中
        ballsArr.push(this);
    }
    //渲染更新球
    Ball.prototype.randomC = function (){
        return parseInt(Math.random()*255);
    }
    Ball.prototype.render = function (){
        ctx.beginPath();
        ctx.fillStyle = this.color;
        ctx.arc(this.x , this.y , this.r, 0, 2*Math.PI, true);
        ctx.fill();
        ctx.closePath();
    }
    Ball.prototype.update = function (){
        this.x += this.dx;
        this.y += this.dy;
        this.r--;
        if( this.r <=0 ){
            this.godie();
        }
    }
    Ball.prototype.godie = function (){
        for( var i = 0; i < ballsArr.length; i++ ){
            //从ballsArr当中找到自身那一项删掉
            if( ballsArr[i] == this ){
                ballsArr.splice(i,1);
            }
        }
    }
    mycanvas.onmousemove = function (ev){
        new Ball(ev.clientX,ev.clientY);
        console.log(ballsArr);
    }
    setInterval(function (){
        //清屏
        ctx.clearRect(0,0,mycanvas.width,mycanvas.height);
        //通过计时器时时监听ballsArr的变化 来进行绘制球
        for( var i = 0; i < ballsArr.length; i++ ){
            ballsArr[i].update();
            ballsArr[i] & ballsArr[i].render();
        }
    },20);
</script>
</html>